import Axios from "axios";
import {message} from "antd"

export const ip = process.env.NODE_ENV === 'production' ? '192.168.20.207' : '47.106.101.161'
// export const ip = process.env.NODE_ENV === 'production' ? '47.107.253.110' : '47.107.253.110'
export const host = "http://" + ip
export const hostWithPort = host + ":22548"
export const flvUrl = (process.env.NODE_ENV === 'production' ? 'http://192.168.20.205' : host) + "/flv"
// export const flvUrl = (process.env.NODE_ENV === 'production' ? 'http://47.107.253.110' : host) + "/flv"
export const wsHost = "ws://" + ip
export const wsHostWithPort = wsHost + ":22548"
export const wsCompareUrl = wsHostWithPort + '/ws/section_status/?'
export const wsAlarmCountUrl = wsHostWithPort + '/ws/levels_alarm_count/'
export const wsUnhandleAlarmUrl = wsHostWithPort + '/ws/unhandled_alarm/'

const baseURL = process.env.NODE_ENV === 'development' ? '' : hostWithPort
const instance = Axios.create({
  baseURL
})


instance.interceptors.request.use(async function (config) {
  config.headers['Authorization'] = `Bearer ${localStorage.getItem("token")}`
  return config
})

instance.interceptors.response.use(function (response) {
  return response.data
}, function (error) {
  // console.log(error);
  const response = error.response
  if (response.data.detail) {
    if (response.status == 401) {
      message.error("登录已经过期，请重新登录")
      setTimeout(() => {
        window.location = "./#/login"
      }, 1000)
    } else {
      message.error(response?.data?.detail)
    }
  } else {
    Object.values(response.data).map((item, index) => {
      Object.values(item).map((value) => {
        message.error(value)
      })
    })
  }

  return Promise.reject(error);
});


export async function getToken(username, password) {
  // if (!sessionStorage.getItem("token")) {
  let res;
  try {
    res = await Axios.post(`${baseURL}/auth/token/`, {
      username,
      password
    })
  } catch (exception) {
    throw exception
  }
  return res
  // res?.data?.access && sessionStorage.setItem("token", res?.data?.access)
  // }
}

export async function requestGet(url, params) {
  return await instance.get(url, {
    params: params
  })
}

export async function requestPost(url, params) {
  return instance.post(url, params)
}

export async function requestDel(url, params) {
  return instance.delete(url, params)
}

export async function requestPatch(url, params) {
  return instance.patch(url, params)
}

